package com.aaa.controller;

import com.aaa.entity.Order;
import com.aaa.entity.Product;
import com.aaa.service.OrderService;
import com.aaa.service.ProductFeign;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.hypermedia.DiscoveredResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Random;

/**
 * @author ：Mickey
 * @date ：Created in 2022/11/17 16:53
 * @description：
 * @modified By：
 * @version:
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ProductFeign productFeign;

    @PostMapping("/saveOrder/{pid}")
    public Order order(@PathVariable("pid")Integer pid){
        log.info(">>客户下单，这时候要调用商品微服务查询商品信息");
        //Product product = restTemplate.getForObject("http://localhost:8001/product/getById/" + pid, Product.class);
        //List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");
        //随机产生一个0-size的下标
        //int index = new Random().nextInt(instances.size());
        //ServiceInstance instance = instances.get(index);
        //log.info("从nacos获取shop-product服务的ip地址{},以及端口号{}",instance.getHost(),instance.getPort());
        //instance.getHost():获取第一个服务名为shop-product的主机地址
        //instance.getPort():获取第一个服务名为shop-product的端口号
        //instance.getUri(); 获取所有
        //String uri = instance.getUri().toString();
        //Product product = restTemplate.getForObject(uri+"/product/getById/" + pid, Product.class);
        //Product product = restTemplate.getForObject("http://shop-product/product/getById/"+pid, Product.class);

        Product product = productFeign.findById(pid);

        log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
        //创建实体类
        Order order = new Order();
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(2);
        order.setUid(2);
        order.setUsername("楚米奇");
        orderService.save(order);

        return order;
    }

}
